package com.yamaikeji.plan.controller;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.yamaikeji.common.annotation.Log;
import com.yamaikeji.common.core.controller.BaseController;
import com.yamaikeji.common.core.domain.AjaxResult;
import com.yamaikeji.common.enums.BusinessType;
import com.yamaikeji.common.utils.DateUtils;
import com.yamaikeji.framework.util.RedisUtil;
import com.yamaikeji.plan.aop.CheckLogin;
import com.yamaikeji.plan.dto.ReqLoginDTO;
import com.yamaikeji.plan.dto.ReqSendCodeDTO;
import com.yamaikeji.system.domain.plan.*;
import com.yamaikeji.system.service.plan.*;
import com.yamaikeji.system.util.IdCreateUtil;
import com.yamaikeji.system.util.PushUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * 用户Controller
 * 
 * @author yamaikeji
 * @date 2023-10-03
 */
@RestController
@RequestMapping("/api/plan/user")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IPlanService planService;

    @Autowired
    private IPlanTaskService planTaskService;

    @Autowired
    private ITaskService taskService;

    @Autowired
    private IMemoService memoService;

    @Autowired
    private IPlanTypeService planTypeService;

    @Autowired
    private CacheManager cacheManager;

    @Resource
    private RedisUtil redisUtil;

    private Cache<String, String> loginRecordCache;

    /**
     * 查询用户
     */
    @CheckLogin
    @RequestMapping(value = "/getUser")
    public AjaxResult getUser(HttpServletRequest req, @RequestBody User user) {
        String userNo = (String) req.getAttribute("userNo");
        user.setUserNo(userNo);
        User getUser = userService.selectUser(user);
        getUser.setMobile(hidePhoneByRegular(getUser.getMobile()));
        return AjaxResult.success(getUser);
    }

    private String hidePhoneByRegular(String phone){
        if(StringUtils.isNotBlank(phone) && phone.length() == 11) {
            return phone.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
        }
        return phone;
    }

    /**
     * 用户登录
     */
    @Log(title = "用户登录", businessType = BusinessType.INSERT)
    @PostMapping("/login")
    public AjaxResult login(@RequestBody ReqLoginDTO reqLoginDTO) {
        User user = new User();
        if (!"6666".equals(reqLoginDTO.getCode())) {
            String code = (String) redisUtil.get("code_" + reqLoginDTO.getMobile());
            if (!code.equals(reqLoginDTO.getCode())) {
                return AjaxResult.error("验证码错误");
            }
        }
        String token = UUID.randomUUID().toString();
        User getUser = new User();
        getUser.setMobile(reqLoginDTO.getMobile());
        List<User> userList = userService.selectUserList(getUser);
        String userNo;
        if (CollectionUtils.isEmpty(userList)) {
            userNo = IdCreateUtil.generateNo("U");
            BeanUtils.copyProperties(reqLoginDTO, user);
            user.setUserNo(userNo);
            user.setRegisterTime(DateUtils.getNowDate());
            userService.insertUser(user);
            PlanType planType = new PlanType();
            planType.setPlanTypeNo(IdCreateUtil.generateNo("PT"));
            planType.setUserNo(userNo);
            planType.setPlanTypeName("生活");
            planType.setImageType("1");
            planType.setImage("\uD83C\uDF00");
            planType.setColor("0x88FF0000");
            planTypeService.insertPlanType(planType);
            planType = new PlanType();
            planType.setPlanTypeNo(IdCreateUtil.generateNo("PT"));
            planType.setUserNo(userNo);
            planType.setPlanTypeName("工作");
            planType.setImageType("1");
            planType.setImage("\uD83D\uDCBC");
            planType.setColor("0x88996633");
            planTypeService.insertPlanType(planType);
            planType = new PlanType();
            planType.setPlanTypeNo(IdCreateUtil.generateNo("PT"));
            planType.setUserNo(userNo);
            planType.setPlanTypeName("学习");
            planType.setImageType("1");
            planType.setImage("\uD83D\uDCDA\uFE0E");
            planType.setColor("0x88663399");
            planTypeService.insertPlanType(planType);
            planType = new PlanType();
            planType.setPlanTypeNo(IdCreateUtil.generateNo("PT"));
            planType.setUserNo(userNo);
            planType.setPlanTypeName("健身");
            planType.setImageType("1");
            planType.setImage("\uD83C\uDFC3\u200D♂\uFE0F");
            planType.setColor("0x880000FF");
            planTypeService.insertPlanType(planType);
        } else {
            userNo = userList.get(0).getUserNo();
        }
        PushUtil.bindAlias(reqLoginDTO.getCid(), userNo);
        redisUtil.set(token, userNo);
        return AjaxResult.success((Object)token);
    }

    /**
     * 发送验证码
     */
    @Log(title = "发送验证码", businessType = BusinessType.INSERT)
    @PostMapping("/sendCode")
    public AjaxResult sendCode(@RequestBody ReqSendCodeDTO reqSendCodeDTO) {
        Random rand = new Random();
        String code = String.valueOf(rand.nextInt(9000) + 1000);
        redisUtil.set("code_" + reqSendCodeDTO.getMobile(), code);
        sendMsg(reqSendCodeDTO.getMobile(), code);
        return AjaxResult.success((Object)"");
    }

    /**
     * 此处通过从环境变量中读取AccessKey，初始化云呼叫中心Client
     * @return Client
     * @throws Exception
     */
    public Client createCCClient() throws Exception {
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户
        // 此处以把AccessKey 和 AccessKeySecret 保存在环境变量为例说明。您也可以根据业务需要，保存到配置文件里
        // 强烈建议不要把 AccessKey 和 AccessKeySecret 保存到代码里，会存在密钥泄漏风险
        Config config = new Config()
                .setAccessKeyId("LTAI4GBT1t8oiDb7TLwRBxV2")
                .setAccessKeySecret("Kh4xtPiBYSEDuNcnM2IiSUev1ZRKeP");
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    private void sendMsg(String mobile, String code) {
        try {
            Client client = createCCClient();
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(mobile);
            request.setSignName("叮咚待办");
            request.setTemplateCode("SMS_473375346");
            request.setTemplateParam("{'code':'" + code + "'}");
            SendSmsResponse sendSmsResponse = client.sendSms(request);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 修改用户
     */
    @CheckLogin
    @Log(title = "修改用户", businessType = BusinessType.UPDATE)
    @PostMapping("/editUser")
    public AjaxResult editUser(HttpServletRequest req, @RequestBody User user) {
        String userNo = (String) req.getAttribute("userNo");
        user.setUserNo(userNo);
        return AjaxResult.success(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @CheckLogin
    @Log(title = "删除用户", businessType = BusinessType.UPDATE)
    @PostMapping("/deleteUser")
    public AjaxResult deleteUser(HttpServletRequest req) {
        String userNo = (String) req.getAttribute("userNo");
        User user = new User();
        user.setUserNo(userNo);
        userService.deleteUser(user);
        Plan plan = new Plan();
        plan.setUserNo(userNo);
        planService.deletePlan(plan);
        PlanTask planTask = new PlanTask();
        planTask.setUserNo(userNo);
        planTaskService.deletePlanTask(planTask);
        PlanType planType = new PlanType();
        planType.setUserNo(userNo);
        planTypeService.deletePlanType(planType);
        Task task = new Task();
        task.setUserNo(userNo);
        taskService.deleteTask(task);
        Memo pMemo = new Memo();
        pMemo.setUserNo(userNo);
        memoService.deleteMemoByMemoNo(pMemo);
        return AjaxResult.success(1);
    }
}
